import ExcelTable from '@/components/exportExcel'
import { getAllMenu } from '@/apis/accessManagement/menu'
import { switchDisable } from '@/apis/accessManagement/menu'
import { deleteMenu } from '@/apis/accessManagement/menu'
import {ActionType, ProFormInstance} from '@ant-design/pro-components'
import { Button, Drawer, Flex, Modal, Tree,message } from 'antd'
import { useRef, useState } from 'react'
import MenuForm from './components/MenuForm'
import { RightOutlined, DownOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom'
enum ComponType {MENU,PAGE,COMPON}

const MenuManage: React.FC = () => {
  useRef<ActionType>()
  useRef<ProFormInstance>()
  const navigate = useNavigate()
  const actionRef = useRef()
  const [messageApi, contextHolder] = message.useMessage()
  const [loading, setLoading] = useState(false)
  const [tableItem, setTableItem] = useState()
  const [addDrawer, setAddDrawer] = useState(false)
  const [addDrawerTitle, setAddDrawerTitle] = useState('新增')
  const [treeData, setTreeData] = useState([])
  const [expandedRowKeys, setExpandedRowKeys] = useState([])
  const [handleMenuId, setHandleMenuId] = useState(null)

    const handleExpand = (expanded:any, record:any) => {
        if (expanded) {
            setExpandedRowKeys((prev) => [...prev, record.menuId])
        } else {
            setExpandedRowKeys((prev) => prev.filter((key) => key !== record.menuId))
        }
    }

    function showAddDrawer(title: string, item?: any) {
        if (item) {
        setTableItem(item)
        }
        setAddDrawerTitle(title)
        setAddDrawer(true)
    }

    function onCloseDrawer() {
        setAddDrawer(false)
    }

    // 禁用/启用菜单
    const subSwitchDisable = async (record:any) => {
        setLoading(true)
        try {
            const response = await switchDisable({
                menuId:parseInt(record.menuId),
                status:record.status === 1?2:1
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('提交成功')
                    window.location.reload()
                    // actionRef.current?.reloadAndRest()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 删除菜单
    const subDeleteMenu = async (record:any) => {
        setLoading(true)
        try {
            const response = await deleteMenu({
                menuId:record.menuId,
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('提交成功')
                    actionRef.current?.reloadAndRest()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

  return (
    <>
        {contextHolder}
        <ExcelTable
            actionRef={actionRef}
            requestFn={ async params => {
                const { pageNum,pageSize,menuName='',isCache=null,roleCode,status=null,menuType=0,path='',updateBy='',startTime='',endTime='', ...newParams } = params; // 处理所需参数名
                const data = await getAllMenu({
                    ...newParams,
                    pagination: {pageNumber:1,showNumber:100}, 
                    menuName:menuName,
                    roleCode:roleCode,
                    status:parseInt(status),
                    menuType:parseInt(menuType),
                    path:path,
                    updateBy:updateBy,
                    startTime:startTime,
                    endTime:endTime,
                    // isCache:parseInt(isCache)
                })
                console.log(data)
                const menuMap = new Map()
                const tree = []
                if(Object.keys(data.data).length > 0){
                    // 初始化 Map
                    data.data.menuInfo.forEach((item: any) => {
                        menuMap.set(item.menuId, { ...item, children: [] })
                    })
                    // 获取节点及其所有子节点
                    const buildTree = (node: any) => {
                        if (node.menuParentId && menuMap.has(node.menuParentId)) {
                            // 添加到父节点的 children
                            const parentNode = menuMap.get(node.menuParentId)
                            parentNode.children.push(node)
                        } else {
                            // 如果没有父节点，视为根节点
                            tree.push(node);
                        }
                        // 递归处理所有子节点
                        data.data.menuInfo
                            .filter((child: any) => child.menuParentId === node.menuId)
                            .forEach((child: any) => buildTree(menuMap.get(child.menuId)))
                    };
                    // 构建树
                    data.data.menuInfo.forEach((item: any) => {
                        if (!item.menuParentId || !menuMap.has(item.menuParentId)) {
                            buildTree(menuMap.get(item.menuId));
                        }
                    });
                }
                // console.log(tree)
                setTreeData(tree)
                // return tree
                }
            }
            dataSource={treeData}
            rowSelection={false}
            rowKey="menuId"
            // toolBarRenderFn={() => [<Button key="add" onClick={() => showAddDrawer('新增')}>新增</Button>]}
            toolBarRenderFn={() => [<Button key="add" onClick={() => navigate('/setting/enterpriseManage/menuManage/addMenu?state=1')}>新增</Button>]}
            expandable={{
                expandedRowKeys, // 控制展开的行
                onExpand: handleExpand, // 展开或收起的回调
                expandIcon: ({ expanded, onExpand, record }) =>
                    record.children && record.children.length > 0 ? (
                    <span onClick={(e) => onExpand(record, e)} style={{ cursor: "pointer" }}>
                        {expanded ? <DownOutlined /> : <RightOutlined />}
                    </span>
                    ) : null, 
            }}
            columns={[
            {
                title: '菜单名称',
                dataIndex: 'menuName',
                hideInTable: true,
            },
            {
                title: '路由地址',
                dataIndex: 'path',
                hideInTable: true
            },
            {
                title: '菜单类型',
                dataIndex: 'menuType',
                hideInTable: true,
                valueType: 'select',
                valueEnum: {
                0: '全部',
                1: '菜单',
                2: '按钮'
                },
            },
            //   {
            //     title: '操作人',
            //     dataIndex: 'updateBy',
            //     hideInTable: true
            //   },
            //   {
            //     title: '操作时间',
            //     dataIndex: 'keyword7',
            //     valueType: 'dateRange',
            //     hideInTable: true
            //   },
            /** table */
            {
                title: '菜单名称',
                dataIndex: 'menuName',
                hideInSearch: true
            },
            {
                title: '排序',
                dataIndex: 'sort',
                hideInSearch: true
            },
            {
                title: '图标',
                dataIndex: 'icon',
                hideInSearch: true
            },
            {
                title: '路由',
                dataIndex: 'path',
                hideInSearch: true
            },
            {
                title: '菜单类型',
                dataIndex: 'menuType',
                hideInSearch: true,
                render: (_, record) => record.menuType === 1 ? '菜单':record.menuType === 2 ? '按钮':'暂无数据',
            },
            {
                title: '状态',
                dataIndex: 'status',
                valueType: 'select',
                valueEnum: {
                '': '全部',
                1: '正常',
                2: '禁用'
                },
                render: (_, record) => 
                    (<span style={{ color: record.status === 1 ? 'green' : record.status === 2 ? 'red' : 'gray' }}>
                    {record.status === 1 ? '正常':record.status === 2 ? '禁用':'暂无数据'}
                    </span>),
            },
            // {
            //     title: '是否缓存',
            //     dataIndex: 'isCache',
            //     valueType: 'select',
            //     valueEnum: {
            //     '': '全部',
            //     1: '启用',
            //     2: '关闭'
            //     },
            //     render: (_, record) => 
            //         (<span style={{ color: record.isCache === 1 ? 'green' : record.isCache === 2 ? 'red' : 'gray' }}>
            //         {record.isCache === 1 ? '启用':record.isCache === 2 ? '关闭':'暂无数据'}
            //         </span>),
            // },
            //   {
            //     title: '状态',
            //     dataIndex: 'type',
            //     hideInSearch: true,
            //     valueEnum: new Map([
            //       [ComponType.MENU, '菜单'],
            //       [ComponType.PAGE, '页面'],
            //       [ComponType.COMPON, '组件']
            //     ])
            //   },
            {
                title: '操作时间',
                dataIndex: 'updateTime',
                hideInSearch: true,
                valueType: 'dateTime'
            },
            {
                title: '操作',
                key: 'option',
                valueType: 'option',
                render: (_, record) => [
                <a key="update" onClick={() => navigate(`/setting/enterpriseManage/menuManage/setMenu?state=2&menuId=${record.menuId}`)}>修改</a>,
                <a key="disabled" onClick={() => {
                    console.log(record)
                    const text = record.status === 1?'禁用':'启用'
                    // setHandleMenuId(record.menuId)
                    Modal.warning({
                        title: '提示',
                        content: `确定${text}该菜单吗?`,
                        okText: '确定',
                        okCancel: true,
                        onOk() {
                            subSwitchDisable(record)
                        },
                    })
                }}>{record.status === 1?'禁用':'启用'}</a>,
                <a key="delete" onClick={() => {
                    Modal.warning({
                    title: '提示',
                    content: '确定删除该菜单吗?',
                    okText: '确定',
                    okCancel: true,
                    onOk() {
                        subDeleteMenu(record)
                    }
                    })
                }}>删除</a>
                ]
            }
            ]}
        />

      <Drawer title={addDrawerTitle} onClose={onCloseDrawer} open={addDrawer} destroyOnClose>
        <MenuForm item={tableItem} onClose={onCloseDrawer}></MenuForm>
      </Drawer>

    </>
  )
}

export default MenuManage
